package com.controller;

import com.entity.Employee;
import com.service.EmployeeService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Data
@RestController
@CrossOrigin
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    private Result success(Object data) {
        return new Result("200", data);
    }

    private Result fail(String msg) {
        return new Result("204", msg);
    }

    /**
     * 200 请求已成功，返回想要的东西。出现此状态码是表示正常状态
     * 204 服务器成功处理，但是没有返回内容
     */

    // 查询所有员工请求
    @GetMapping()
    public Result selectEmployeeAll() {
        List<Employee> employees = employeeService.selectEmployeeAll();
        return employees != null && !employees.isEmpty() ? success(employees) : fail("未查询到数据");
    }

    // 用 id 查询员工请求
    @GetMapping("/{id}")
    public Result selectEmployeeById(@PathVariable String id) {
        Employee employee = employeeService.selectEmployeeById(Integer.parseInt(id));
        return employee != null ? success(employee) : fail("未查询到数据");
    }

    // 用 name 查询员工请求
    @GetMapping(params = "name")
    public Result selectEmployeeByName(String name) {
        Employee employee = employeeService.selectEmployeeByName(name);
        return employee != null ? success(employee) : fail("未查询到数据");
    }


    // 用 id 删除员工请求
    @DeleteMapping("/{id}")
    public Result deleteEmployeeById(@PathVariable String id) {
        return employeeService.deleteEmployeeById(Integer.parseInt(id)) ? success("删除成功") :fail("删除失败");
    }

    // 新增员工请求
    /**
     * {
     * "empno": 0,
     * "ename": "陈俊杰",
     * "job": "程序员",
     * "mgr": 1006,
     * "hiredate": "2001-02-20",
     * "sal": 16000.0,
     * "comm": 3000.0,
     * "deptno": 20
     * }
     */
    @PostMapping()
    public Result insertEmployee(@RequestBody Employee employee) {
        return employeeService.insertEmployee(employee) ? success("新增成功") :fail("新增失败");
    }

    // 修改员工请求
    @PutMapping()
    public Result updateEmployeeById(@RequestBody Employee employee) {
        return employeeService.updateEmployeeById(employee) ? success("修改成功") :fail("修改失败");
    }
}
